package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        //缓存穿透 (一般采用存null值到数据库或者布隆过滤)
//        Shop shop = queryWithPassThrough(id);

        //互斥锁解决缓存击穿(又热点key问题)
        // 优点：(没有额外内存损耗，保持一致性，实现简单)
        // 缺点：(线程需要等待，性能受影响，可能有死锁问题)
//        Shop shop = queryWithMutex(id);

        //逻辑过期解决缓存击穿(又热点key问题)
        // 优点：(线程无需等待，性能较好)
        // 缺点：(不保证一致性，有额外内存损耗，实现复杂)
//        Shop shop = queryWithLogicalExpire(id);

        //缓存穿透(工具类方法)(一般采用存null值到数据库或者布隆过滤)
        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id,
                Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

/*        //逻辑过期解决缓存击穿(工具类方法)(又热点key问题)
        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id,
                Shop.class, this::getById, 20L, TimeUnit.SECONDS);*/

        if (shop == null) {
            return Result.fail("店铺不存在!");
        }
        return Result.ok(shop);
    }


    //创建一个线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    //逻辑过期解决缓存击穿
    public Shop queryWithLogicalExpire(Long id) {
        //从redis查询商品缓存，判断是否存在(返回的是json格式)
        String json = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if (StrUtil.isBlank(json)) {
            //如果不存在，直接返回null
            return null;
        }
        //命中，需要判断过期时间，先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        //判断是否过期
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())) {
            //未过期（当前时间在过期时间之前，所以未过期）
            return shop;
        }
        //已过期，需要缓存重建，
        //获取互斥锁，（判断互斥锁是否为空）
        boolean isLock = tryLock(LOCK_SHOP_KEY + id);
        if (isLock) {
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //重建缓存（实际开发设置为30min）
//                this.saveShop2Redis(id,20L);
                    //测试,设置为20s
                    this.saveShop2Redis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unLock(LOCK_SHOP_KEY + id);
                }

            });
        }
        //获取互斥锁成功，开启独立线程实现缓存重建

        //返回商品信息

        return shop;
    }


    //互斥锁
    public Shop queryWithMutex(Long id) {
        //从redis查询商品缓存，判断是否存在(返回的是json格式)
        String json = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if (StrUtil.isNotBlank(json)) {
            //转为java对象
            return JSONUtil.toBean(json, Shop.class);
        }
        //判断命中的是否是空值
        if (json != null) {
            //返回一个错误信息
            return null;
        }


        Shop shop = null;
        try {
            //实现缓存重建，获取互斥锁，判断是否获取成功
            boolean isLock = tryLock(LOCK_SHOP_KEY + id);
            if (!isLock) {
                //获取锁失败，休眠并重试获取互斥锁(递归)
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //获取锁成功
            //查询数据库
            shop = getById(id);
            //模拟重建时的延迟，来测试
            Thread.sleep(200);
            if (shop == null) {
                //将空值写入redis防止redis缓存穿透，(注意这里存的是空字符串(" ")，而不是null(""))
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, " ", CACHE_NULL_TTL, TimeUnit.MINUTES);

                return null;
            }
            //写入redis(之前先将查到的java对象转为json)
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //释放互斥锁
            unLock(LOCK_SHOP_KEY + id);
        }

        return shop;
    }


    //缓存穿透方法封装起来了(后来不用了，用工具类里面的缓存穿透)
    public Shop queryWithPassThrough(Long id) {
        //从redis查询商品缓存，判断是否存在(返回的是json格式)
        String json = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if (StrUtil.isNotBlank(json)) {
            //转为java对象
            return JSONUtil.toBean(json, Shop.class);
        }
        //判断命中的是否是空值
        if (json != null) {
            //返回一个错误信息
            return null;
        }
        //不存在，查询数据库
        Shop shop = getById(id);
        if (shop == null) {
            //将空值写入redis防止redis缓存穿透，(注意这里存的是空字符串(" ")，而不是null(""))
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, " ", CACHE_NULL_TTL, TimeUnit.MINUTES);

            return null;
        }
        //存在，写入redis(之前先将查到的java对象转为json)
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }

    //尝试获取锁
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    //释放锁
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    //存储店铺信息，逻辑过期时间//缓存预热
    public void saveShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
        //查询店铺数据
        Shop shop = getById(id);
        //模拟缓存有一定的延迟，设置休眠一下
        Thread.sleep(200);
        //封住逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    //更新数据库，然后更新redis缓存（删除缓存）
    @Override
    @Transactional //如果操作redis有抛出异常，统一事务进行回滚
    public Result update(Shop shop) {
        //先对id做非空判断
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }
        updateById(shop);
        //根据shop的id删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //判断是否需要地理坐标查询
        if (x == null || y == null) {
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        //计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        //查询redis，按照距离排序分页shopId ,distance  from参数没法指定，只能从0开始
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );
        //解析id,根据id查询数据库，最后返回数据
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            //没有下一页，也就是到了最后一页，结束
            return Result.ok(Collections.emptyList());
        }
        //截取从from到end的部分
        ArrayList<Long> ids = new ArrayList<>(list.size());
        HashMap<String, Distance> distanceHashMap = new HashMap<>(list.size());
        //skip查到最后可能会查到空，导致sql语句出错
        list.stream().skip(from).forEach(result -> {
            //获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            //获取距离
            Distance distance = result.getDistance();
            distanceHashMap.put(shopIdStr, distance);

        });
        //根据id查询shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceHashMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);
    }
}
